import { useEffect, useRef, useState } from "react";
import {
  Button,
  Checkbox,
  Form,
  Slider,
  DatePicker,
  Modal,
  Input,
  Upload,
  UploadProps,
  message,
  Space,
  Pagination,
} from "antd";
import {
  AimOutlined,
  CloseOutlined,
  ShoppingCartOutlined,
} from "@ant-design/icons";
import styles from "./index.module.scss";

import areaDrawing from "@/assets/images/areaDrawing.png";
import coordinate from "@/assets/images/coordinate.png";
import file from "@/assets/images/file.png";

import rectangle from "@/assets/images/Rectangle.png";
import circle from "@/assets/images/Circle.png";
import polygon from "@/assets/images/Polygon.png";
import { NavLink } from "react-router-dom";

export default function Search() {
  const { T } = window;
  let mapRef: any = useRef(null);
  let lay;
  var handler: any;
  const { RangePicker } = DatePicker;
  const [formCon, setFormCon]: any = useState(false);
  const [map, setMap]: any = useState(null);
  const [mapInitialized, setMapInitialized]: any = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [dataDesc, setDataDesc]: any = useState({});
  const [selectType, setSelectType]: any = useState(1);

  // 地图初始化
  useEffect(() => {
    if (mapRef.current && !mapInitialized) {
      var imageURL =
        "http://t0.tianditu.gov.cn/img_w/wmts?" +
        "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
        "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=8efd1b376f2a021fcd3b3fd49a592eca";
      lay = new T.TileLayer(imageURL, { minZoom: 1, maxZoom: 18 });
      var config = { layers: [lay] };
      const newMap = new T.Map(mapRef.current, config);
      newMap.centerAndZoom(new T.LngLat(102.0, 20.0), 4);
      var ctrl = new T.Control.MapType();
      newMap.addControl(ctrl);
      setMap(newMap);
      setMapInitialized(true);
      //创建标注工具
      var config2 = {
        showLabel: true,
        color: "blue",
        weight: 3,
        opacity: 0.5,
        fillColor: "#FFFFFF",
        fillOpacity: 0.5,
      };
      new T.PolygonTool(newMap, config2);
    }
  }, []);
  // 矩形
  const openRectangleTool = () => {
    if (handler) handler.close();
    handler = new T.RectangleTool(map, { follow: true });
    handler.open();
  };
  // 圆形
  const openCircleTool = () => {
    if (handler) handler.close();
    handler = new T.CircleTool(map, { follow: true });
    handler.open();
  };
  // 多边形
  const openPolygonTool = () => {
    if (handler) handler.close();
    handler = new T.PolygonTool(map);
    handler.open();
  };
  // 上传文件
  const [fileValue, steFileValue]: any = useState({}); //接口返回的保存地址和文件名称
  const handleChange: UploadProps["onChange"] = (item: any) => {
    // 限制上传格式
    const isJpgOrPng =
      item.file.type === "application/zip" ||
      item.file.type === "application/vnd.google-earth.kml+xml";
    if (!isJpgOrPng) {
      message.error("File format error");
      return false;
    }
    if (item.fileList.length != 0) {
      // 调用上传接口
      const formData = new FormData();
      formData.append("upload_file", item.file);
      //   UploadAPI(formData).then((res: any) => {
      //     // console.log(res.data);
      //     steFileValue(res.data);
      //   });
    }
  };

  // 查询表单;
  const [form] = Form.useForm();
  const [satelliteData, setSatelliteData]: any = useState({
    GF1: { PMS: false, WAV: false },
    GF6: { PMS: false, WAV: false },
    ZY302: { DLC: false, MUX: false, NAD: false },
    CBERS04: { PSM: false, P10: false, MUX: false },
  });
  const handleAllSatellitesChange = (e: any) => {
    const allChecked = e.target.checked;
    setSatelliteData({
      GF1: { PMS: allChecked, WAV: allChecked },
      GF6: { PMS: allChecked, WAV: allChecked },
      ZY302: { DLC: allChecked, MUX: allChecked, NAD: allChecked },
      CBERS04: { PSM: allChecked, P10: allChecked, MUX: allChecked },
    });
    form.setFieldsValue({
      GF1: allChecked ? ["PMS", "WAV"] : [],
      GF6: allChecked ? ["PMS", "WAV"] : [],
      ZY302: allChecked ? ["DLC", "MUX", "NAD"] : [],
      CBERS04: allChecked ? ["PSM", "P10", "MUX"] : [],
    });
  };
  const onReset = () => {
    form.resetFields();
    map.clearOverLays();
    setSatelliteData({
      GF1: { PMS: false, WAV: false },
      GF6: { PMS: false, WAV: false },
      ZY302: { DLC: false, MUX: false, NAD: false },
      CBERS04: { PSM: false, P10: false, MUX: false },
    });
  };
  const onConfirm = () => {
    console.log(form.getFieldsValue());
    // 这里可以添加获取表单数据的逻辑
    setFormCon(true);
    onReset();
  };
  // 表单默认值
  const initialValues = {
    cloudAmount: 48,
    GF1: ["PMS", "WAV"],
  };
  // 查询结果数据
  const result = [
    {
      id: 1,
      cover: polygon,
      satellite: "GF6",
      sensor: "PMS",
      title: "GF6_WFV_E99.1_N48.6_20230920_L1A1420356320.tar.gz",
    },
    {
      id: 2,
      cover: polygon,
      satellite: "GF1",
      sensor: "WAV",
      title: "GF6_WFV_E99.1_N48.6_20230920_L1A1420356320.tar.gz",
    },
    {
      id: 3,
      cover: polygon,
      satellite: "ZY302",
      sensor: "NAD",
      title: "GF6_WFV_E99.1_N48.6_20230920_L1A1420356320.tar.gz",
    },
    {
      id: 4,
      cover: polygon,
      satellite: "ZY302",
      sensor: "NAD",
      title: "GF6_WFV_E99.1_N48.6_20230920_L1A1420356320.tar.gz",
    },
  ];
  // 分页
  const [page, setPage] = useState(1); //当前页码
  const total = result.length;
  const lastTodoInView = page * 3;
  const firstTodoInView = lastTodoInView - 3;
  const todosForDisplay: any = result.slice(firstTodoInView, lastTodoInView);
  const handlePageChange = (pageNumber: any) => {
    setPage(pageNumber);
  };
  // 是否登录
  const [isLoginOpen, setIsLoginOpen]: any = useState(false);
  const isLogin = localStorage.getItem("GY1");
  const handleOk = (values: any) => {
    console.log(values);
    // login({ email: values.email, password: values.password }).then(
    // (res: any) => {
    // console.log(res);
    // if (res.code === 200) {
    localStorage.setItem("GY1", JSON.stringify("awd"));
    location.href = "/";
    // } else {
    // message.error(res.msg);
    // }
    // };
    // );
    setIsModalOpen(false);
  };
  //购物车
  const [selectedItems, setSelectedItems]: any = useState([]); // 存储选中项的ID
  const handleAllToCart = () => {
    console.log(selectedItems);
  };
  const handleToCart = (id: any) => {
    console.log(id);
  };
  // 全选或全不选
  const handleSelectAll = (checked: any) => {
    if (checked) {
      setSelectedItems(todosForDisplay.map((item: any) => item.id));
    } else {
      setSelectedItems([]);
    }
  };
  // 当点击单个数据的选择框时，更新选中状态
  const handleSelectItem = (id: any) => {
    const isSelected = selectedItems.includes(id);
    let newSelectedItems = [];
    if (isSelected) {
      newSelectedItems = selectedItems.filter((itemId: any) => itemId !== id);
    } else {
      newSelectedItems = [...selectedItems, id];
    }
    setSelectedItems(newSelectedItems);
  };

  return (
    <div>
      {/* 表单 */}
      <div className={styles.fixedBox}>
        <div className={styles.topTitle}>Image product Search</div>
        <Form
          form={form}
          layout="vertical"
          className={styles.formStyle}
          initialValues={initialValues} // 设置初始值
        >
          <span className={styles.formTitle}>Spatial location</span>
          {/* 空间位置 */}
          <div className={styles.selectTypeBox}>
            <div
              className={selectType === 1 ? styles.selected : ""}
              onClick={() => {
                setSelectType(1);
              }}
            >
              <img src={areaDrawing} />
              <p>Area drawing</p>
            </div>
            <div
              className={selectType === 2 ? styles.selected : ""}
              onClick={() => {
                setSelectType(2);
              }}
            >
              <img src={coordinate} />
              <p>Coordinate</p>
            </div>
            <div
              className={selectType === 3 ? styles.selected : ""}
              onClick={() => {
                setSelectType(3);
              }}
            >
              <img src={file} />
              <p>File</p>
            </div>
          </div>
          {selectType === 1 ? (
            <div className={styles.areaDrawingBox}>
              <div
                className={styles.areaDrawing}
                onClick={() => {
                  openRectangleTool();
                }}
              >
                <img src={rectangle} />
                <p>Rectangle</p>
              </div>
              <div
                className={styles.areaDrawing}
                onClick={() => {
                  openCircleTool();
                }}
              >
                <img src={circle} />
                <p>Circle</p>
              </div>
              <div
                className={styles.areaDrawing}
                onClick={() => {
                  openPolygonTool();
                }}
              >
                <img src={polygon} />
                <p>Polygon</p>
              </div>
            </div>
          ) : selectType === 2 ? (
            <div className={styles.coordinateBox}>
              <Space>
                <Form.Item className={styles.inputItem} name="leftLongitude">
                  <Input placeholder="Upper left longitude" />
                </Form.Item>
                <Form.Item className={styles.inputItem} name="leftLatitude">
                  <Input placeholder="Upper left latitude" />
                </Form.Item>
              </Space>
              <Space>
                <Form.Item className={styles.inputItem} name="rightLongitude">
                  <Input placeholder="Lower right longitude" />
                </Form.Item>
                <Form.Item className={styles.inputItem} name="rightLatitude">
                  <Input placeholder="Lower right latitude" />
                </Form.Item>
              </Space>
            </div>
          ) : (
            <div className={styles.fileBox}>
              <p>
                Please click the icon to upload. Support to the shapefile (needs
                .zip file including .shx,.dbf, .shp and .prf files) or .kml
                file.
              </p>
              <Form.Item
                name="file"
                valuePropName="file"
                labelCol={{ span: 25 }}
              >
                <Upload
                  onChange={handleChange}
                  beforeUpload={() => {
                    return false;
                  }}
                  maxCount={1}
                >
                  <div
                    style={{
                      width: 80,
                      border: "1px solid black",
                      textAlign: "center",
                      cursor: "pointer",
                      marginTop: "10px",
                    }}
                  >
                    选择文件
                  </div>
                </Upload>
              </Form.Item>
            </div>
          )}
          {/* 采集时间 */}
          <Form.Item
            name="collectTime"
            label={<span className={styles.formTitle}>Acquisition time</span>}
          >
            <RangePicker />
          </Form.Item>
          {/* 云量 */}
          <Form.Item
            name="cloudAmount"
            label={<span className={styles.formTitle}>Cloudage</span>}
          >
            <Slider
              tooltip={{ open: true }}
              // Slider轨道的颜色
              railStyle={{ backgroundColor: "#02051b" }}
              // Slider选中部分的颜色
              trackStyle={{ backgroundColor: "#3ea0f9" }}
            />
          </Form.Item>
          {/* 卫星数据 */}
          <Form.Item>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
              }}
            >
              <label className={styles.formTitle}>Satellite data</label>
              <Checkbox
                onChange={handleAllSatellitesChange}
                className={styles.formTitle}
              >
                Select all
              </Checkbox>
            </div>
            <Checkbox.Group>
              <Form.Item
                name="GF1"
                label={
                  <span style={{ color: "#3fa0fe", fontSize: "10px" }}>
                    GF1
                  </span>
                }
              >
                <Checkbox.Group
                  value={Object.keys(satelliteData.GF1).filter(
                    (key) => satelliteData.GF1[key]
                  )}
                  onChange={(checkedValues) => {
                    const newValues: any = {};
                    Object.keys(satelliteData.GF1).forEach((key) => {
                      newValues[key] = checkedValues.includes(key);
                    });
                    setSatelliteData((prevData: any) => ({
                      ...prevData,
                      GF1: newValues,
                    }));
                  }}
                >
                  <Checkbox value="PMS" className={styles.checkColor}>
                    PMS
                  </Checkbox>
                  <Checkbox value="WAV" className={styles.checkColor}>
                    WAV
                  </Checkbox>
                </Checkbox.Group>
              </Form.Item>
              <Form.Item
                name="GF6"
                label={
                  <span style={{ color: "#3fa0fe", fontSize: "10px" }}>
                    GF6
                  </span>
                }
              >
                <Checkbox.Group
                  value={Object.keys(satelliteData.GF6).filter(
                    (key) => satelliteData.GF6[key]
                  )}
                  onChange={(checkedValues) => {
                    const newValues: any = {};
                    Object.keys(satelliteData.GF6).forEach((key) => {
                      newValues[key] = checkedValues.includes(key);
                    });
                    setSatelliteData((prevData: any) => ({
                      ...prevData,
                      GF6: newValues,
                    }));
                  }}
                >
                  <Checkbox value="PMS" className={styles.checkColor}>
                    PMS
                  </Checkbox>
                  <Checkbox value="WAV" className={styles.checkColor}>
                    WAV
                  </Checkbox>
                </Checkbox.Group>
              </Form.Item>
              <Form.Item
                name="ZY302"
                label={
                  <span style={{ color: "#3fa0fe", fontSize: "10px" }}>
                    ZY302
                  </span>
                }
              >
                <Checkbox.Group
                  value={Object.keys(satelliteData.ZY302).filter(
                    (key) => satelliteData.ZY302[key]
                  )}
                  onChange={(checkedValues) => {
                    const newValues: any = {};
                    Object.keys(satelliteData.ZY302).forEach((key) => {
                      newValues[key] = checkedValues.includes(key);
                    });
                    setSatelliteData((prevData: any) => ({
                      ...prevData,
                      ZY302: newValues,
                    }));
                  }}
                >
                  <Checkbox value="DLC" className={styles.checkColor}>
                    DLC
                  </Checkbox>
                  <Checkbox value="MUX" className={styles.checkColor}>
                    MUX
                  </Checkbox>
                  <Checkbox value="NAD" className={styles.checkColor}>
                    NAD
                  </Checkbox>
                </Checkbox.Group>
              </Form.Item>
              <Form.Item
                name="CBERS04"
                label={
                  <span style={{ color: "#3fa0fe", fontSize: "10px" }}>
                    CBERS04
                  </span>
                }
              >
                <Checkbox.Group
                  value={Object.keys(satelliteData.CBERS04).filter(
                    (key) => satelliteData.CBERS04[key]
                  )}
                  onChange={(checkedValues) => {
                    const newValues: any = {};
                    Object.keys(satelliteData.CBERS04).forEach((key) => {
                      newValues[key] = checkedValues.includes(key);
                    });
                    setSatelliteData((prevData: any) => ({
                      ...prevData,
                      CBERS04: newValues,
                    }));
                  }}
                >
                  <Checkbox value="PSM" className={styles.checkColor}>
                    PSM
                  </Checkbox>
                  <Checkbox value="P10" className={styles.checkColor}>
                    P10
                  </Checkbox>
                  <Checkbox value="MUX" className={styles.checkColor}>
                    MUX
                  </Checkbox>
                </Checkbox.Group>
              </Form.Item>
            </Checkbox.Group>
          </Form.Item>
          {/* 重置与提交 */}
          <Form.Item style={{ display: "flex", justifyContent: "flex-end" }}>
            <Button className={styles.resetBtn} onClick={onReset}>
              Reset
            </Button>
            <Button type="primary" onClick={onConfirm}>
              Confirm
            </Button>
          </Form.Item>
        </Form>
      </div>
      {/* 查询结果 */}
      {formCon && (
        <div className={styles.formConfirm}>
          <div className={styles.topTitle}>
            Search result
            <CloseOutlined
              onClick={() => {
                setFormCon(false);
              }}
              style={{ marginLeft: "160px" }}
            />
          </div>
          <div className={styles.formStyle}>
            {/* 数据 */}
            <div className={styles.spaceBtw}>
              <div style={{ padding: "10px" }}>Total 3 pieces of data</div>
              <div
                style={{
                  display: "flex",
                  padding: "10px",
                  alignItems: "center",
                }}
              >
                <Checkbox onChange={(e) => handleSelectAll(e.target.checked)} />
                <p style={{ margin: "0 8px" }}>Select all</p>
                {isLogin ? (
                  <ShoppingCartOutlined
                    style={{ fontSize: "15px" }}
                    onClick={handleAllToCart}
                  />
                ) : (
                  <ShoppingCartOutlined
                    style={{ fontSize: "15px" }}
                    onClick={() => {
                      setIsLoginOpen(true);
                    }}
                  />
                )}
              </div>
            </div>
            {todosForDisplay.map((item: any) => {
              const isSelected = selectedItems.includes(item.id); // 检查当前项是否被选中
              return (
                <div className={styles.dataItem} key={item.id}>
                  {/* 拇指图 */}
                  <div>
                    <img src={item.cover} />
                  </div>
                  <div>
                    {/* 上方 */}
                    <div className={styles.spaceBtw}>
                      {/* 左边标签 */}
                      <div className={styles.spaceBtw}>
                        <div
                          className={styles.labels}
                          style={{ marginRight: "5px" }}
                        >
                          {item.satellite}
                        </div>
                        <div className={styles.labels}>{item.sensor}</div>
                      </div>
                      {/* 右边图标 */}
                      <div>
                        <AimOutlined style={{ fontSize: "15px" }} />
                        {isLogin ? (
                          <ShoppingCartOutlined
                            onClick={() => handleToCart(item.id)}
                            style={{ margin: "0 8px ", fontSize: "15px" }}
                          />
                        ) : (
                          <ShoppingCartOutlined
                            onClick={() => setIsLoginOpen(true)}
                            style={{ margin: "0 8px ", fontSize: "15px" }}
                          />
                        )}
                        <Checkbox
                          checked={isSelected}
                          onChange={() => handleSelectItem(item.id)}
                        />
                      </div>
                    </div>
                    {/* 下方 */}
                    <div
                      className={styles.navTitle}
                      onClick={() => {
                        setDataDesc(item);
                        setIsModalOpen(true);
                      }}
                    >
                      {item.title}
                    </div>
                  </div>
                </div>
              );
            })}
            <Pagination
              className={styles.pageStyle}
              defaultCurrent={1}
              current={page} //当前页码
              total={total} //总页数
              pageSize={3} //存储每页上的项目数
              onChange={handlePageChange}
            />
          </div>
        </div>
      )}
      {/* 查询结果_信息 */}
      <Modal
        title="数据集信息"
        open={isModalOpen}
        footer={null}
        onCancel={() => {
          setIsModalOpen(false);
        }}
        width={1000}
      >
        <div>
          <img
            style={{ width: "100%", height: "200px" }}
            src={dataDesc.cover}
          />
          <div className={styles.innerTitle}>影像基本信息</div>
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <div>卫星：{dataDesc.satellite}</div>
            <div>传感器：{dataDesc.sensor}</div>
            <div>采集时间：2022-12-30 10:26:5</div>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <div>左上角经/纬度：117.104425/40.734503</div>
            <div>右上角经/纬度：117.373493/40.687368</div>
            <div>景中心经/纬度：</div>
          </div>
          <div className={styles.innerTitle}>系统生产参数</div>
          <div style={{ height: "100px" }}></div>
        </div>
      </Modal>
      {/* 地图 */}
      <div
        style={{
          width: "100%",
          height: "91vh",
        }}
        ref={mapRef}
      ></div>
      {/* 登录 */}
      <Modal
        title="Login"
        open={isLoginOpen}
        onCancel={() => {
          setIsLoginOpen(false);
        }}
        footer={false}
      >
        <Form
          name="normal_login"
          onFinish={handleOk}
          layout="vertical"
          style={{ width: "85%", margin: "50px auto" }}
        >
          <Form.Item
            label="Account"
            name="email"
            rules={[{ required: true, message: "Please input your Email!" }]}
          >
            <Input placeholder="Place enter email" />
          </Form.Item>
          <Form.Item
            label="Password"
            name="password"
            rules={[{ required: true, message: "Please input your Password!" }]}
          >
            <Input type="password" placeholder="Place enter password" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ width: "100%" }}>
              Log in
            </Button>
          </Form.Item>
          <Form.Item>
            <div style={{ display: "flex", justifyContent: "space-between" }}>
              <NavLink to={""}>Forgot password</NavLink>
              <NavLink
                to={"register"}
                onClick={() => {
                  setIsModalOpen(false);
                }}
              >
                register now!
              </NavLink>
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
